<template>
  <div class="app-page">
    <el-form ref="form" inline :model="temp" :rules="tempRules">
      <div class="phone-search bottom-margin">
        <div>
          <el-form-item label="来电号码：" prop="phone">
            <el-input v-model="temp.phone" placeholder="请输入来电号码" />
          </el-form-item>
          <el-form-item>
            <el-button v-permission="2071" type="primary" @click="onTelSearch">查询</el-button>
          </el-form-item>
        </div>
        <span
          v-if="callDate"
          class="callTime"
        >来电时间：{{ callDate }} 等待数：{{ callNum }}</span>
      </div>
      <el-row :gutter="20" class="bottom-margin">
        <el-col :span="14">
          <el-card class="bottom-margin">
            <div slot="header">
              <span>客户信息</span>
            </div>
            <div class="client">
              <div class="client-item">
                <div>
                  <span>客户编号：</span><span>{{ clientSelected.csmCode }}</span>
                </div>
                <div>
                  <span>客户类型：</span><span>{{
                    clientSelected.csmType
                      ? clientSelected.csmType == 1
                        ? "居民"
                        : clientSelected.csmType === 2
                          ? "商业"
                          : ""
                      : ""
                  }}</span>
                </div>
              </div>
              <div class="client-item">
                <div>
                  <span>客户名称：</span><span>{{ clientSelected.csmName }}</span>
                </div>
                <div>
                  <span>所属机构：</span><span>{{ clientSelected.nearStationName }}</span>
                </div>
              </div>
            </div>
            <div>
              <span>身份证号码：</span><span>{{ clientSelected.sfzh }}</span>
            </div>
          </el-card>
          <el-card>
            <div slot="header">
              <span>最近的配送信息</span>
            </div>
            <el-table :height="250" :data="shippingInfoData">
              <el-table-column label="选择" width="100">
                <template slot-scope="scope">
                  <!-- <el-checkbox v-model="scope.row.select" @change="shippingInfoChange(scope.row)" /> -->
                  <el-radio
                    v-model="scope.row.select"
                    class="select-radio"
                    :label="true"
                    @change="shippingInfoChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="contactName" label="联系人" />
              <el-table-column prop="telephone" label="联系电话" />
              <el-table-column prop="addressText" label="联系地址" />
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="10">
          <el-card>
            <div slot="header">
              <span>快速查询</span>
            </div>
            <el-form-item label="条件类型：" prop="type">
              <el-select
                v-model="temp.type"
                placeholder="请选择条件类型"
                @change="typeChange"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="temp[typeVal[temp.type - 1]]" />
            </el-form-item>
            <el-form-item>
              <el-button v-permission="2072" type="primary" @click="fastSearch">快速查找</el-button>
            </el-form-item>
            <el-table :height="340" :data="clientData.data">
              <el-table-column prop="csmCode" label="编号" />
              <el-table-column label="选择" width="100">
                <template slot-scope="scope">
                  <!-- <el-checkbox v-model="scope.row.select" @change="clientChange(scope.row)" /> -->
                  <el-radio
                    v-model="scope.row.select"
                    class="select-radio"
                    :label="true"
                    @change="clientChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="address" label="客户信息">
                <template slot-scope="scope">
                  <div>
                    <span>身份证:</span><span>{{ scope.row.sfzh }}</span>
                  </div>
                  <div>
                    <span>电话:</span><span>{{ scope.row.csmRgPhone }}</span>
                  </div>
                  <div>
                    <span>编号:</span><span>{{ scope.row.csmCode }}</span>
                  </div>
                  <div>
                    <span>所属机构:</span><span>{{ scope.row.nearStationName }}</span>
                  </div>
                  <div>
                    <span>地址:</span><span>{{ scope.row.csmRgAddress }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- <el-pagination
              :current-page="clientData.currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="clientData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="clientData.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            /> -->
          </el-card>
        </el-col>
      </el-row>

      <el-card class="bottom-margin">
        <div slot="header">
          <span>配送和转派机构</span>
        </div>
        <div class="shipping">
          <div>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="联系人："
                  label-width="120px"
                  prop="contactName"
                  class="col-input-full"
                >
                  <el-input
                    v-model="temp.contactName"
                    maxlength="15"
                    placeholder="请输入联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="联系电话："
                  label-width="120px"
                  prop="telephone"
                  class="redlabel col-input-full"
                >
                  <el-input
                    v-model="temp.telephone"
                    maxlength="15"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="所在区域："
                  prop="area"
                  label-width="120px"
                  class="costormLabel redlabel"
                >
                  <el-select
                    v-model="temp.province"
                    placeholder="请选择省"
                    @change="provinceChange"
                  >
                    <el-option
                      v-for="item in provinceList"
                      :key="item.value"
                      :label="item.areaName"
                      :value="item.areaCode"
                    />
                  </el-select>
                  <el-select
                    v-model="temp.city"
                    placeholder="请选择市"
                    @change="cityChange"
                  >
                    <el-option
                      v-for="item in cityList"
                      :key="item.value"
                      :label="item.areaName"
                      :value="item.areaCode"
                    />
                  </el-select>
                  <el-select
                    v-model="temp.area"
                    placeholder="请选择区"
                    @change="areaChange"
                  >
                    <el-option
                      v-for="item in areaList"
                      :key="item.value"
                      :label="item.areaName"
                      :value="item.areaCode"
                    />
                  </el-select>
                  <!-- <el-select v-model="temp.street" placeholder="请选择街道" @change="streetChange">
                    <el-option
                      v-for="item in streetList"
                      :key="item.value"
                      :label="item.areaName"
                      :value="item.areaCode"
                    />
                  </el-select> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="联系地址："
                  label-width="120px"
                  prop="address"
                  class="col-input-full"
                >
                  <!-- <el-input
                    v-model="temp.address"
                    maxlength="50"
                    placeholder="请输入联系地址"
                  /> -->

                  <el-autocomplete
                    ref="suggestionInput"
                    v-model="temp.address"
                    v-scrollLoad="getLoad"
                    :maxlength="50"
                    :debounce="300"
                    popper-class="address-autocomplete"
                    :fetch-suggestions="queryAddressSearch"
                    placeholder="请输入联系地址"
                    :trigger-on-focus="false"
                    @select="handleSelect"
                  >
                    <template slot-scope="{ item }">
                      <div class="name">{{ item.value }}</div>
                      <span class="addr">{{ item.address }}</span>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item
                  label="门牌号："
                  label-width="120px"
                  prop="doorplate"
                  class="col-input-full"
                >
                  <el-input
                    v-model="temp.doorplate"
                    maxlength="50"
                    placeholder="请输入门牌号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item
                  label="楼层："
                  label-width="80px"
                  prop="floor"
                  class="col-input-full"
                >
                  <el-input-number
                    v-model="temp.floor"
                    :controls="false"
                    :min="1"
                    label="label"
                    @blur="floorChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="责任机构："
                  prop="orgId"
                  label-width="120px"
                  class="col-input-full"
                >
                  <el-select
                    v-model="temp.orgId"
                    placeholder="请选择责任机构"
                    @change="shopChange"
                  >
                    <el-option
                      v-for="item in shopList"
                      :key="item.value"
                      :label="item.orgName"
                      :value="item.orgId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="处理人："
                  prop="userId"
                  label-width="120px"
                  class="col-input-full"
                >
                  <el-select v-model="temp.userId" placeholder="请选择处理人">
                    <el-option
                      v-for="item in handlerList"
                      :key="item.value"
                      :label="item.userName"
                      :value="item.userId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>

      <el-card class="bottom-margin">
        <div slot="header">
          <span>这次的商品信息</span>
        </div>
        <el-form-item label="商品分类：" prop="gTypeId">
          <el-select
            v-model="temp.gTypeId"
            placeholder="请选择商品分类"
            @change="goodTypeChange"
          >
            <el-option
              v-for="item in goodTypeList"
              :key="item.value"
              :label="item.gtName"
              :value="item.gtId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品选择：" prop="goods">
          <el-select
            v-model="temp.goods"
            placeholder="请选择商品选择"
            @change="goodsChange"
          >
            <el-option
              v-for="item in goodsList"
              :key="item.value"
              :label="item.goodsName"
              :value="item.goodsId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-permission="2073"
            type="primary"
            :loading="$loadingPlugin.onAdd"
            @click="onAdd(1)"
          >添加</el-button>
        </el-form-item>
        <el-table :data="commodityData" :show-summary="true">
          <el-table-column prop="goodsName" label="商品名称" />
          <el-table-column prop="originPrice" label="市价" />
          <el-table-column
            prop="purchaseQuantity"
            label="数量"
            min-width="130px"
          >
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.purchaseQuantity"
                :controls="false"
                :min="1"
                :max="100"
                label=""
                @blur="purchaseQuantityChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="discountPrice" label="优惠" />
          <el-table-column prop="deliveryCost" label="远距配送费" />
          <el-table-column prop="floorFun" label="上楼费" />
          <el-table-column prop="tip" label="服务费" />
          <el-table-column prop="salePrice" label="总金额" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <i
                class="el-icon-delete"
                style="color: red; cursor: pointer;"
                @click="goodsDelete(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="bottom-margin">
        <div slot="header">
          <span>其他</span>
        </div>
        <div>
          <el-form-item label="补充说明：" prop="description">
            <el-checkbox-group
              v-model="temp.description"
              @change="descriptionChange"
            >
              <el-checkbox :label="1">加急</el-checkbox>
              <el-checkbox :label="2">需发票</el-checkbox>
              <el-checkbox :label="3">自提</el-checkbox>
              <el-checkbox :label="4">月结</el-checkbox>
              <el-checkbox :label="5">需回执</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="备注：">
            <el-input
              v-model="temp.remark"
              type="textarea"
              :rows="2"
              maxlength="30"
              placeholder="请输入备注"
            />
          </el-form-item>
        </div>
        <div class="footer">
          <el-button
            v-permission="2074"
            type="primary"
            :loading="isSubmit"
            @click="onSubmit"
          >提交</el-button>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script>
  import {
    findAddressList,
    findCustomers,
    findGoodsList,
    findGoodTypeList,
    findShopList,
    findUserList,
    phoneOrderCalculate,
    phoneOrderSubmit,
    selectAreaCode
  } from '@/api'
  import { getLocalSearch } from '@/utils/BMap'
  import store from '@/store'
  import { debounce } from '@/utils/debounce'
  export default {
    name: 'call-order-add',
    directives: {
      scrollLoad: {
        bind(el, binding, vnode) {
          const wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
          const listDom = el.querySelector(
            '.el-autocomplete-suggestion__list'
          )
          wrapDom.addEventListener(
            'scroll',
            e => {
              const condition = ((listDom.offsetHeight - wrapDom.offsetHeight) + 37 - 0.3) - wrapDom.scrollTop
              if (condition < 0 && !vnode.context.loading) {
                // 滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
                binding.value()
              }
            },
            false
          )
        }
      }
    },
    props: {
      currentPhone: {
        type: String,
        default: '',
        required: false
      },
      callDate: {
        type: String,
        default: '',
        required: false
      },
      callNum: {
        type: Number,
        default: 0,
        required: false
      },
      editableTabsValue: {
        type: String || Number,
        default: '',
        required: false
      }
    },
    data() {
      const validMobile = (rule, value, callback) => {
        const reg = /^1\d{10}$/
        const tel = /^0\d{2,3}-?\d{7,8}$/
        if (!value) {
          callback(new Error('请输入联系方式'))
        } else if (value && !(reg.test(value) || tel.test(value))) {
          callback(new Error('请输入正确的联系方式'))
        } else {
          callback()
        }
      }
      return {
        provinceList: [],
        cityList: [],
        areaList: [],
        // streetList: [],
        temp: {
          csmRgPhone: undefined,
          sfzh: undefined,
          csmName: undefined,
          csmCode: undefined,
          cardNo: undefined,
          contactName: '',
          telephone: '',
          address: '',
          doorplate: '',
          floor: '',
          orgId: '',
          userId: '',
          gTypeId: '',
          goods: '',
          description: [],
          remark: '',
          province: '',
          city: '',
          area: '',
          createTime: '',
          // street: '',
          phone: '',
          type: 1,
          latitude: '',
          longitude: '',
          provinceName: '',
          cityName: '',
          countryName: '',
          streetName: '',
          updateStatus: 0,
          specCode: ''
        },
        tempRules: {
          contactName: [
            { required: true, message: '联系人不能为空', trigger: 'change' }
          ],
          telephone: [{ validator: validMobile, trigger: 'change' }],
          address: [
            { required: true, message: '联系地址不能为空', trigger: 'change' }
          ],
          orgId: [
            { required: true, message: '请选择责任机构', trigger: 'change' }
          ],
          userId: [{ required: true, message: '请选择处理人', trigger: 'change' }]
        },
        typeList: [
          {
            label: '电话号码',
            value: 1
          },
          {
            label: '身份证',
            value: 2
          },
          {
            label: '客户名称',
            value: 3
          },
          {
            label: '客户编号',
            value: 4
          },
          {
            label: '充值卡',
            value: 5
          }
        ],
        typeVal: ['csmRgPhone', 'sfzh', 'csmName', 'csmCode', 'cardNo'],
        clientData: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          data: []
        },
        shippingInfoData: [],
        commodityData: [],
        clientSelected: {},
        shippingInfoSelected: {},
        shopList: [],
        handlerList: [],
        goodTypeList: [],
        goodsList: [],
        isSubmit: false,
        oldAddress: [],
        slectAddress: {},
        addressInfo: {
          page_num: 0,
          page_size: 10
        },
        suggestionCb: undefined,
        suggestionList: []
      }
    },
    watch: {
      currentPhone: function(val) {}
    // editableTabsValue: function(val) {
    //   this.getData()
    // }
    },
    created() {
      this.getProvinceData()
      this.getData()
    },
    methods: {
      getData() {
        if (this.currentPhone && this.currentPhone === this.editableTabsValue) {
          this.temp.phone = this.currentPhone
          this.onTelSearch()
        }
      },
      async getAreaData(value) {
        const res = await selectAreaCode({ areaCode: value || 0 })
        return res.data
      },
      async getProvinceData() {
        this.provinceList = await this.getAreaData(0)
      },

      async provinceChange() {
        this.temp.city = ''
        this.temp.area = ''
        // this.temp.street = ''
        this.temp.address = ''
        this.cityList = await this.getAreaData(this.temp.province)
        this.clearAddressInfo()
      },
      async cityChange() {
        this.temp.area = ''
        // this.temp.street = ''
        this.temp.address = ''
        this.areaList = await this.getAreaData(this.temp.city)
        this.clearAddressInfo()
      },
      async areaChange() {
        // this.temp.street = ''
        this.temp.address = ''
        // this.streetList = await this.getAreaData(this.temp.area)
        this.clearAddressInfo()
      },
      async streetChange() {
      // this.temp.address = ''
      },

      handleSizeChange(val) {
        this.clientData.pageSize = val
        this.getClientData()
      },
      handleCurrentChange(val) {
        this.clientData.currentPage = val
        this.getClientData()
      },
      // 重置
      resetForm() {
        this.clientData = {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          data: []
        }
        this.shippingInfoData = []
        this.commodityData = []
        this.clientSelected = {}
        this.shippingInfoSelected = {}
        this.shopList = []
        this.handlerList = []
        this.goodTypeList = []
        this.goodsList = []
        this.slectAddress = {}
        this.temp.province = ''
        this.temp.city = ''
        this.temp.country = ''
        // this.temp.street = ''
        this.temp.doorplate = ''
        this.temp.floor = ''
        this.$refs['form'].resetFields()
      },
      // 客户列表
      async getClientData() {
        this.resetForm()
        const params = {
          pageIndex: this.clientData.currentPage,
          pageSize: 20,
          params: {
            csmRgPhone: this.temp.csmRgPhone,
            sfzh: this.temp.sfzh,
            csmName: this.temp.csmName,
            csmCode: this.temp.csmCode,
            cardNo: this.temp.cardNo
          }
        }
        const res = await findCustomers(params)
        if (res) {
          if (res.data.length > 0) {
            this.clientData.data = res.data.map(item => ({
              select: false,
              ...item
            }))
            this.defalutClientData()
          } else {
            this.$message.error('未查找到客户信息')
          }
        }
      },

      defalutClientData() {
        if (this.clientData.data.length > 0) {
          this.clientData.data[0].select = true
          this.clientSelected = this.clientData.data[0]
        } else {
          this.clientSelected = {}
        }
        this.getAddressList()
      },
      // 配送信息
      async getAddressList() {
        const params = {
          csmId: this.clientSelected.csmId,
          corpCode: this.clientSelected.corpCode
        }
        const res = await findAddressList(params)
        if (res) {
          const shippingInfoData = res.data.map((item, index) => ({
            index,
            select: false,
            ...item,
            addressText: item.floor
              ? item.address + (item.doorplate || '') + `(楼层:${(item.floor || '')})`
              : item.address
          }))
          this.shippingInfoData = JSON.parse(JSON.stringify(shippingInfoData))
          this.oldAddress = JSON.parse(JSON.stringify(shippingInfoData))
        }
        if (this.shippingInfoData.length > 0) {
          this.shippingInfoData[0].select = true
          this.shippingInfoSelected = this.shippingInfoData[0]
        } else {
          this.getClear()
        }
        this.getFillShippingInfo()
      },
      getClear() {
        this.shippingInfoSelected = {}
        this.shopList = []
        this.handlerList = []
        this.goodTypeList = []
        this.goodsList = []
        this.commodityData = []
        this.temp.orgId = ''
        this.temp.userId = ''
        this.temp.gTypeId = ''
        this.temp.goods = ''
      },
      // 获取配送和转派机构
      async getFillShippingInfo() {
        const {
          contactName,
          telephone,
          provinceCode,
          cityCode,
          countryCode,
          address,
          floor,
          doorplate,
          latitude,
          longitude,
          createTime
        } = this.shippingInfoSelected
        this.temp.contactName = contactName
        this.temp.telephone = telephone
        this.temp.province = provinceCode
        await this.provinceChange()
        this.temp.city = cityCode
        await this.cityChange()
        this.temp.area = countryCode
        await this.areaChange()
        // this.temp.street = streetCode
        this.temp.createTime = createTime
        this.temp.floor = floor
        this.temp.address = address
        this.temp.doorplate = doorplate
        this.temp.latitude = latitude
        this.temp.longitude = longitude
        this.getShopList()
      },
      // 责任机构
      async getShopList() {
        const params = {
          corpCode: this.clientSelected.corpCode
        }
        const res = await findShopList(params)
        this.shopList = res.data
      },
      // 选择机构
      shopChange() {
        if (this.temp.gTypeId || this.temp.goods) {
          this.$confirm('变更机构需要重新筛选商品，您确定吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.temp.gTypeId = ''
              this.temp.goods = ''
              this.commodityData = []
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
        }
        this.temp.userId = ''
        this.getUserList()
        this.getGoodTypeList()
      },
      // 处理人
      async getUserList() {
        const params = {
          corpCode: this.clientSelected.corpCode,
          orgId: this.temp.orgId
        }
        const res = await findUserList(params)
        this.handlerList = res.data
      },
      // 商品分类
      async getGoodTypeList() {
        const params = {
          corpCode: this.clientSelected.corpCode
        }
        const res = await findGoodTypeList(params)
        this.goodTypeList = res.data
      },
      goodTypeChange() {
        this.temp.goods = ''
        this.goodsList = []
        this.getGoodsList()
      },
      // 商品列表
      async getGoodsList() {
        const params = {
          corpCode: this.clientSelected.corpCode,
          orgId: this.temp.orgId,
          gTypeId: this.temp.gTypeId
        }
        const res = await findGoodsList(params)
        this.goodsList = res.data
      },
      // 验证
      checkOrder() {
        if (!this.temp.orgId) {
          this.$message.warning('请先选择责任机构')
          return false
        }
        if (!this.temp.gTypeId) {
          this.$message.warning('请选择商品分类')
          return false
        } else if (!this.temp.goods) {
          this.$message.warning('请选择商品')
          return false
        }
        return true
      },
      async handleOrder(count) {
        const commodityData = this.commodityData
        const isExit = commodityData.find(
          item => item.goodsId === this.temp.goods
        )
        if (isExit) {
          commodityData.forEach((item, index) => {
            if (item.goodsId === this.temp.goods) {
              commodityData[index].purchaseQuantity++
            }
          })
        } else {
          commodityData.push({
            goodsId: this.temp.goods,
            purchaseQuantity: count,
            specCode: this.temp.specCode
          })
        }

        return commodityData
      },
      // 添加商品
      async onAdd(count) {
        if (this.commodityData.length >= 5) {
          this.$message.warning('最多下单5个不同类型的商品')
          return
        }
        if (!this.checkOrder()) {
          return
        }
        const commodityData = await this.handleOrder(count)
        this.updateGoods(commodityData)
      },
      // 删除计算
      async getCalculate(commodityData) {
        return new Promise(async(resolve, reject) => {
          const params = {
            orderGoodsList: commodityData,
            shop: {
              orgId: this.temp.orgId
            },
            customerInfo: this.clientSelected,
            address: {},
            isPickUp: this.temp.description
              ? this.temp.description.includes(3)
                ? 1
                : 0
              : 0
          }

          await this.getAddressUpdateStatus()

          // const res = await phoneOrderCalculate(params)
          // if (res && res.data && res.data.orderGoodsList) {
          //   this.commodityData = res.data.orderGoodsList
          // } else {
          //   this.commodityData = []
          // }

          // params.address = {
          //   latitude: this.temp.latitude,
          //   longitude: this.temp.longitude,
          //   floor: this.temp.floor,
          //   provinceName: this.temp.provinceName,
          //   cityName: this.temp.cityName,
          //   streetName: this.shippingInfoSelected.streetName,
          //   address: this.temp.address,
          //   createTime: this.temp.createTime
          // }

          const {
            contactName,
            telephone,
            address,
            doorplate,
            province,
            provinceName,
            city,
            cityName,
            area,
            countryName,
            floor,
            updateStatus,
            latitude,
            longitude
          } = this.temp
          const addressData = {
            contactName,
            telephone,
            address,
            doorplate,
            provinceCode: province,
            provinceName,
            cityCode: city,
            cityName,
            countryCode: area,
            countryName,
            floor,
            updateStatus,
            latitude,
            longitude
          }
          Object.keys(this.shippingInfoSelected).forEach(item => {
            if (!Object.keys(addressData).includes(item)) {
              addressData[item] = this.shippingInfoSelected[item]
            }
          })
          params.address = addressData

          phoneOrderCalculate(params)
            .then(res => {
              if (res && res.data && res.data.orderGoodsList) {
                this.commodityData = res.data.orderGoodsList
              }
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
        })
      },
      onSearch() {},
      onTelSearch() {
        // this.$refs['form'].resetFields()
        if (this.temp.phone) {
          this.temp.type = 1
          this.temp[this.typeVal[this.temp.type - 1]] = this.temp.phone
          this.getClientData()
        }
      },
      // 快速查找
      fastSearch() {
        if (!this.temp[this.typeVal[this.temp.type - 1]]) {
          this.$message.error('条件输入框不能为空')
          return
        }
        this.getClientData()
      },
      typeChange(val) {
        this.typeVal.forEach((item, index) => {
          if (index + 1 !== val) {
            this.temp[item] = undefined
          }
        })
      },

      // 客户信息
      clientChange(row) {
        this.getClear()
        this.clientSelected = row
        this.clientData.data.forEach((item, index) => {
          if (item.csmId !== this.clientSelected.csmId) {
            this.clientData.data[index].select = false
          }
        })
        this.getAddressList()
      },
      // 配送信息
      shippingInfoChange(row) {
        this.getClear()
        this.shippingInfoSelected = row
        this.shippingInfoData.forEach((item, index) => {
          if (item.index !== row.index) {
            this.shippingInfoData[index].select = false
          }
        })
        this.getFillShippingInfo()
      },
      // 删除商品
      async goodsDelete(row) {
        this.commodityData = this.commodityData.filter(
          item => item.goodsId !== row.goodsId
        )
        const commodityData = await this.handleCommodityData()
        this.getCalculate(commodityData)
      },
      // 数量改变
      async purchaseQuantityChange(row) {
        if (row.purchaseQuantity > 0) {
          const commodityData = await this.handleCommodityData()
          this.getCalculate(commodityData)
        } else {
          this.$message.warning('数量最小为1')
        }
      },
      updateGoods(commodityData) {
        this.getCalculate(commodityData)
          .then(res => {})
          .catch(err => {
            console.log(err, '编辑失败--------')
            const isExistIndex = this.commodityData.findIndex(
              item => item.goodsId === this.temp.goods
            )
            if (isExistIndex || isExistIndex === 0) {
              if (this.commodityData[isExistIndex].purchaseQuantity > 1) {
                this.commodityData[isExistIndex].purchaseQuantity--
              } else {
                this.commodityData.splice(isExistIndex, 1)
              }
            } else {
              this.commodityData = this.commodityData.filter(
                item => item.goodsId !== this.temp.goods
              )
            }
          })
      },
      // 提交
      async onSubmit() {
        if (!(this.clientSelected && this.clientSelected.csmCode)) {
          this.$message.error('请选择客户信息后操作')
        }
        this.$refs.form.validate(async valid => {
          if (valid) {
            if (!this.temp.province || !this.temp.city || !this.temp.area) {
              this.$message.error('请选择完整的所在区域')
              return
            }
            if (!this.commodityData.length > 0) {
              this.$message.error('请至少选择一件商品')
              return
            }
            const params = {
              orderGoodsList: this.commodityData,
              shop: {
                orgId: this.temp.orgId
              },
              customerInfo: this.clientSelected,
              address: {},
              userInfo: await this.getUserInfo(),
              isPickUp: this.temp.description
                ? this.temp.description.includes(3)
                  ? 1
                  : 0
                : '',
              isUrgent: this.temp.description
                ? this.temp.description.includes(1)
                  ? 1
                  : 0
                : '',
              isInvoice: this.temp.description
                ? this.temp.description.includes(2)
                  ? 1
                  : 0
                : '',
              paymentMethod: this.temp.description
                ? this.temp.description.includes(4)
                  ? 16
                  : 0
                : '',
              reStatus: this.temp.description
                ? this.temp.description.includes(5)
                  ? 2
                  : 1
                : '',
              remark: this.temp.remark,
              phone: this.temp.phone
            }
            await this.getAddressUpdateStatus()
            const {
              contactName,
              telephone,
              address,
              doorplate,
              province,
              provinceName,
              city,
              cityName,
              area,
              countryName,
              floor,
              updateStatus,
              latitude,
              longitude
            } = this.temp
            const addressData = {
              contactName,
              telephone,
              address,
              doorplate,
              provinceCode: province,
              provinceName,
              cityCode: city,
              cityName,
              countryCode: area,
              countryName,
              floor,
              updateStatus,
              latitude,
              longitude
            }
            Object.keys(this.shippingInfoSelected).forEach(item => {
              if (!Object.keys(addressData).includes(item)) {
                addressData[item] = this.shippingInfoSelected[item]
              }
            })
            params.address = addressData
            params.address.idNumber = this.clientSelected.sfzh
            this.isSubmit = true
            phoneOrderSubmit(params)
              .then(res => {
                if (res) {
                  this.$message.success('操作成功')
                  this.resetForm()

                  this.temp.remark = ''
                  this.isSubmit = false
                  this.updateData(this.currentPhone)
                }
              })
              .catch(err => {
                console.log(err)
                this.isSubmit = false
              })
          }
        })
      },
      updateData(activeName) {
        const pbxList = store.state.app.PBXData
        const activeIndex = pbxList.findIndex(item => item.p5 === activeName)
        store.state.app.PBXData.splice(activeIndex, 1)
        store.state.app.PBXData[activeIndex] = {
          p5: activeName,
          done: true
        }
      },
      async getUserInfo() {
        const userInfo = this.handlerList.find(
          item => item.userId === this.temp.userId
        )
        if (userInfo) {
          const { userId, userCode, userName } = userInfo
          return { userId, userCode, userName }
        }
      },
      // 获取经纬度
      async getAddressUpdateStatus() {
        const oldAddress = this.oldAddress.find(
          item => item.id === this.shippingInfoSelected.id
        )
        const {
          contactName,
          telephone,
          address,
          province,
          city,
          area,
          street,
          floor
        } = this.temp
        const newAddress = { contactName, telephone, address, floor }
        newAddress.provinceCode = province
        newAddress.cityCode = city
        newAddress.countryCode = area
        newAddress.streetCode = street

        if (newAddress && this.shippingInfoSelected.id) {
          const flag = Object.keys(newAddress).some(
            item => newAddress[item] !== oldAddress[item]
          )
          if (flag) {
            await this.handelLocation()
          } else {
            this.temp.latitude = this.shippingInfoSelected.latitude
            this.temp.longitude = this.shippingInfoSelected.longitude
            this.temp.provinceName = this.shippingInfoSelected.provinceName
            this.temp.cityName = this.shippingInfoSelected.cityName
            this.temp.countryName = this.shippingInfoSelected.countryName
          // this.temp.streetName = this.shippingInfoSelected.streetName
          }
          this.temp.updateStatus = flag ? 1 : 0
        } else {
          await this.handelLocation()
          this.temp.updateStatus = 1
        }
      },
      async handelLocation() {
        const province = this.getAreaName(this.temp.province, this.provinceList)
        const city = this.getAreaName(this.temp.city, this.cityList)
        const area = this.getAreaName(this.temp.area, this.areaList)
        // const street = this.getAreaName(this.temp.street, this.streetList)
        // const addressText = province + city + area + street + this.temp.address
        // const latAndLon = await addressToLocation(addressText)
        // if (latAndLon && latAndLon.latitude && latAndLon.longitude) {
        //   this.temp.latitude = latAndLon.latitude
        //   this.temp.longitude = latAndLon.longitude
        // }
        this.temp.provinceName = province
        this.temp.cityName = city
        this.temp.countryName = area
      // this.temp.streetName = street
      },
      getAreaName(code, list) {
        const codeItem = list.find(item => item.areaCode === code)
        if (codeItem && codeItem.areaName) {
          return codeItem.areaName
        } else {
          return ''
        }
      },
      async getCommodityData() {
        const commodityData = await this.handleCommodityData()
        this.getCalculate(commodityData)
      },
      descriptionChange(val) {
        this.getCommodityData()
      },

      floorChange() {
        if (this.temp.floor && this.commodityData.length > 0) {
          this.getCommodityData()
        }
      },
      // 地址模糊匹配
      handleSelect(item) {
        this.clearAddressInfo()
        const latAndLon = item.location
        if (latAndLon && latAndLon.lat && latAndLon.lng) {
          this.temp.latitude = latAndLon.lat
          this.temp.longitude = latAndLon.lng
          this.slectAddress = {
            provinceName: this.temp.provinceName,
            cityName: this.temp.cityName,
            countryName: this.temp.countryName,
            address: this.temp.address
          }
        }
      },
      clearAddressInfo() {
        // this.temp.gTypeId = ''
        // this.temp.goods = ''
        this.temp.latitude = ''
        this.temp.longitude = ''
        this.commodityData = []
      },
      async queryAddressSearch(queryString, cb) {
        const { provinceName, cityName, countryName } = this.temp
        if (
          queryString !== this.slectAddress.address
        ) {
          this.addressInfo.page_num = 0
        }
        if (
          queryString !== this.shippingInfoSelected.address &&
          queryString !== this.slectAddress.address
        ) {
          this.clearAddressInfo()
        } else {
          if (
            queryString === this.shippingInfoSelected.address &&
            provinceName === this.shippingInfoSelected.provinceName &&
            cityName === this.shippingInfoSelected.cityName &&
            countryName === this.shippingInfoSelected.countryName
          ) {
            this.temp.latitude = this.shippingInfoSelected.latitude
            this.temp.longitude = this.shippingInfoSelected.longitude
          }
          if (
            queryString === this.slectAddress.address &&
            provinceName === this.slectAddress.provinceName &&
            cityName === this.slectAddress.cityName &&
            countryName === this.slectAddress.countryName
          ) {
            this.temp.latitude = this.temp.latitude
            this.temp.longitude = this.temp.longitude
          }
          if (this.commodityData.length > 0) {
            const commodityData = await this.handleCommodityData()
            this.getCalculate(commodityData)
          }
        }
        this.getAddressSuggestionList(cb)
      },
      async getAddressSuggestionList(cb) {
        // const { provinceName, cityName, countryName } = this.temp

        const province = this.getAreaName(this.temp.province, this.provinceList)
        const city = this.getAreaName(this.temp.city, this.cityList)
        const area = this.getAreaName(this.temp.area, this.areaList)
        const params = {
          page_num: this.addressInfo.page_num,
          page_size: this.addressInfo.page_size,
          queryString: (province || '') + (city || '') + (area || '') + this.temp.address,
          city
        }
        const res = await getLocalSearch(params)
        if (res && res.results && res.results.length > 0) {
          const list = res.results.map(item => ({
            value: item.name,
            location: item.location,
            address: item.address,
            adcode: item.adcode
          }))
          if (cb) {
            this.suggestionList = list
            cb(this.suggestionList)
          } else {
            this.$nextTick(() => {
              if (params.page_num > 0) {
                this.suggestionList = this.suggestionList.concat(list)
                this.$refs.suggestionInput.suggestions = this.suggestionList
              }
            })
          }
        } else {
          if (cb) {
            this.$message.error('未匹配到正确地址信息，请重新输入详细地址')
            cb([])
          }
        }
      },
      getLoad() {
        debounce(console.log('i am load'))
        this.addressInfo.page_num++
        this.$refs.suggestionInput.fetchSuggestions()
      },
      handleCommodityData() {
        const commodityData = this.commodityData.map(item => ({
          goodsId: item.goodsId,
          purchaseQuantity: item.purchaseQuantity,
          specCode: item.specCode
        }))

        return commodityData
      },
      // 商品选择变化
      goodsChange(e) {
        const goodsSelect = this.goodsList.find(
          item => item.goodsId === this.temp.goods
        )
        this.temp.specCode = goodsSelect.specCode
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  height: auto;
  padding: 0;
  margin: 0;
  background: 0;
  .el-tabs {
    & /deep/ .el-tabs__header {
      background-color: #fff;
    }
    .el-pagination {
      white-space: normal;
    }
  }
  .phone-search {
    display: flex;
    justify-content: space-between;
    padding: 18px 32px 0 32px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    .callTime {
      padding-top: 10px;
    }
  }
  .el-card {
    border-radius: 10px;
  }
  .bottom-margin {
    margin-bottom: 20px;
  }
  .shipping {
    .el-form-item {
      display: flex;
      &/deep/ .el-form-item__label {
        width: 120px;
        min-width: 120px;
      }
    }
    .col-input-full {
      &/deep/ .el-form-item__content {
        width: 100%;

        .el-autocomplete,
        .el-select,
        .el-input-number {
          width: 100%;
        }
      }
    }
    .costormLabel {
      .el-select {
        width: 150px;
      }
    }
    .redlabel {
      &/deep/ .el-form-item__label {
        &::before {
          margin-right: 4px;
          color: #f56c6c;
          content: "*";
        }
      }
    }
  }
  .footer {
    text-align: center;
  }
  .client {
    display: flex;
    margin-bottom: 10px;
    .client-item {
      div {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10px;
        span {
          display: block;
        }
        span:nth-child(1) {
          min-width: 80px;
        }
        span:nth-child(2) {
          min-width: 120px;
        }
      }
      div:nth-last-child(1) {
        margin-bottom: 0;
      }
    }
    .client-item:nth-child(1) {
      margin-right: 20px;
    }
  }
  .select-radio {
    & /deep/ .el-radio__label {
      display: none;
    }
  }
}
</style>

<style lang="scss">
.address-autocomplete {
  li {
    padding: 7px;
    line-height: normal;
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
  }
}
</style>
